package com.miracle.shiro;

import com.miracle.entity.Perms;
import com.miracle.entity.User;
import com.miracle.service.UserService;
import com.miracle.util.JWTUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户自定义Realm
 * @author jie.xi
 * @date 2022年04月21日 15:09
 */

@Service
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     * @author jie.xi
     * @date 2022/4/21 15:14
     */
    @Override
    public boolean supports(AuthenticationToken token){
        return token instanceof JWTToken;
    }


    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获取身份信息
        String primaryPrincipal = (String) principals.getPrimaryPrincipal();
        System.out.println("调用授权验证"+primaryPrincipal);
        String username = JWTUtil.getUsername(principals.toString());
        //根据主身份信息获取角色和权限信息
        User user = userService.findRolesByUserName(username);
        System.out.println(user);
        //授权角色信息
        if(!CollectionUtils.isEmpty(user.getRoles())){
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role -> {
                simpleAuthorizationInfo.addRole(role.getName());
                //权限信息
                List<Perms> perms = userService.findPermsByRoleId(role.getId());
                if(!CollectionUtils.isEmpty(perms)){
                    perms.forEach(perm->{
                        simpleAuthorizationInfo.addStringPermission(perm.getName());
                    });
                }
            });
            return simpleAuthorizationInfo;
        }
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String token = (String) authenticationToken.getCredentials();
        //解密获得username,用于和数据库对比
        String username = JWTUtil.getUsername(token);
        if(username == null){
            throw new AuthenticationException("token invalid");
        }
        User user = userService.getUser(username);
        if(!JWTUtil.verify(token,username,user.getPassword())){
            throw new AuthenticationException("用户名或者密码错误");
        }
        return new SimpleAuthenticationInfo(token,token,this.getName());
    }
}
